// CountPOAServer.java: The Count Server main program
package Server1;

import org.omg.PortableServer.*;
import org.omg.CosNaming.*;

class CountPOAServer
{ 
	static public void main(String[] args)
	{ 
		try
		{ // Initialize the ORB
	      org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);
	       
	      // get a reference to the root POA
	      POA rootPOA = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
	
	      // Create policies for our persistent POA
	      org.omg.CORBA.Policy[] policies = {
	         rootPOA.create_lifespan_policy(LifespanPolicyValue.TRANSIENT)
	      };
	
	      // Create myPOA with the right policies
	      POA myPOA = rootPOA.create_POA( "count_poa", rootPOA.the_POAManager(), policies );
	
	      // Activate the POA manager
	      rootPOA.the_POAManager().activate();
	
	      // get a reference to the Naming Service root context
	      org.omg.CORBA.Object nameServiceObj = orb.resolve_initial_references("NameService");
	      if (nameServiceObj == null) 
	      {
	        System.out.println("nameServiceObj = null");
	        return;
	      }
	
	      NamingContextExt nameService = NamingContextExtHelper.narrow(nameServiceObj);
	      if (nameService == null) 
	      {
	        System.out.println("nameService = null");
	        return;
	      }
	
	      CountPOAServant[] countServants = new CountPOAServant[1000];
	      
	      long startTime = System.currentTimeMillis();
	      
	      for(int x = 0; x < 1000; x++) {
		      // Create the servant
		      CountPOAServant countServant = new CountPOAServant();
	    	  
		      // Decide on the ID for the servant
		      byte[] countId = "MyCount".concat(String.valueOf(x+1)).getBytes();
		
		      // Activate the servant with the ID on myPOA
		      myPOA.activate_object_with_id(countId, countServant);
	      }
	      
	      long stopTime = System.currentTimeMillis();
	      
	      System.out.println("Avg time to create and activate each counter = " + ((stopTime - startTime)/1000000f) + " msecs");
	      
	      for(int x = 0; x < 1000; x++) {
		      // bind the Count object in the Naming service
		      NameComponent[] countName = {new NameComponent("countName".concat(String.valueOf(x+1)), "")};
		      nameService.rebind(countName, myPOA.servant_to_reference(countServants[x]));
	      }

	      // Wait for incoming requests
	      orb.run();
	      
	    } catch(Exception e)
	    { 
	    	System.err.println(e);
	    }
	}
}
